package com.thinkfit.jy.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.common.lib.constant.EventBusEvent;
import com.common.lib.utils.BaseUtils;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.SettingNewActivity;
import com.thinkfit.jy.activity.SimpleBluetoothActivity;
import com.thinkfit.jy.activity.SimpleWifiActivity;
import com.thinkfit.jy.bluetooth.Bluetooth;
import com.thinkfit.jy.serialport.SerialPortManager;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;

/**
 * 右上角简易设置弹窗
 */
public class SimpleSettingViewUtils implements View.OnClickListener {

    private static SimpleSettingViewUtils simpleSettingViewUtils;
    WindowManager windowManager;
    Context mContext;
    FragmentActivity mActivity;
    boolean isFist = true;
    int brigthnessProgress,mBrigthnessProgress,volumeProgress,mSoundProgress;
    View inflate;
    WindowManager.LayoutParams layoutParams;
    private AudioManager mAudioManager;
    ConstraintLayout clBg,clWifiAndBluetooth,clSetting,clWifi,clBluetooth;
    RangeSeekBar rsbSound,rsbBrigthness;
    TextView tvWifiName,tvBuletoothName;
    boolean isFirstBrigthness = true;
    boolean isFirstSound = true;
    public static SimpleSettingViewUtils getInstance(){
        if(simpleSettingViewUtils == null){
            simpleSettingViewUtils = new SimpleSettingViewUtils();
        }
        return simpleSettingViewUtils;
    }


    public void initView(Context context, FragmentActivity activity){
        mContext = context;
        mActivity = activity;
        if(windowManager == null){
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        if(inflate == null){
            inflate = LayoutInflater.from(context).inflate(R.layout.item_simple_setting, null);
            clBg = inflate.findViewById(R.id.cl_bg);
            clWifiAndBluetooth = inflate.findViewById(R.id.cl_wifi_and_bluetooth);
            clBluetooth = inflate.findViewById(R.id.cl_bluetooth);
            clWifi = inflate.findViewById(R.id.cl_wifi);
            clSetting = inflate.findViewById(R.id.cl_setting);
            rsbSound = inflate.findViewById(R.id.rsb_sound);
            rsbBrigthness = inflate.findViewById(R.id.rsb_brigthness);
            tvWifiName = inflate.findViewById(R.id.tv_wifi_name);
            tvBuletoothName = inflate.findViewById(R.id.tv_buletooth_name);

        }

        initBrigthness();
        initSound();
        initWifiAndBluetooth();

        clBg.setOnClickListener(this);
        clWifi.setOnClickListener(this);
        clBluetooth.setOnClickListener(this);
        clSetting.setOnClickListener(this);

        if(layoutParams == null){
            layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );
            layoutParams.gravity = Gravity.CENTER;
        }


        if(isFist){
            isFist = false;
            windowManager.addView(inflate,layoutParams);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }

    }

    public void initWifiAndBluetooth(){
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String ssid = wifiInfo.getSSID().replace("\"", "");
        if (ssid.equals("<unknown ssid>")) {
            tvWifiName.setText(R.string.app_not_connect);
        } else {
            tvWifiName.setText(ssid);
        }

        initBluetooth();
    }

    @SuppressLint("MissingPermission")
    public void initBluetooth(){
        if(BluetoothOrder.getInstance().isConnect()){
            String bluetoothName = BluetoothOrder.getInstance().getBluetoothName();
            tvBuletoothName.setText(bluetoothName);
        }else {

            List<BluetoothDevice> bleConnectDevice = BluetoothOrder.getInstance().getBleConnectDevice(mContext);
            if (bleConnectDevice.size() > 0) {
                for (BluetoothDevice item : bleConnectDevice) {
                    if(item.getBluetoothClass() == null){
                        return;
                    }
                    int styleMajor = item.getBluetoothClass().getMajorDeviceClass();//获取蓝牙主要分类
                    if(BluetoothClass.Device.Major.AUDIO_VIDEO == styleMajor){
                        tvBuletoothName.setText(item.getName());
                        return;
                    }

                }

            }else {
                tvBuletoothName.setText(mContext.getString(R.string.app_not_connect));
            }
        }

    }

    public void initBrigthness(){
        if(inflate == null){
            return;
        }
        int currentBrigthness = SystemUtils.getBrightness(mContext);
        //最大亮度
        int mMaxBrigthness = SystemUtils.getMaxBrightness(mContext);
        brigthnessProgress = (int)((currentBrigthness/(mMaxBrigthness*1f))*100f);
        HashMap<Object, Object> map = new HashMap<>();
        rsbBrigthness.setRange(0,100);
        rsbBrigthness.setProgress(brigthnessProgress);
//        tvBrigthnessNum.setText(brigthnessProgress+"%");
        rsbBrigthness.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFirstBrigthness){
                    isFirstBrigthness = false;
                    return;
                }

                mBrigthnessProgress = (int) (leftValue + 0.0001);
//                tvBrigthnessNum.setText(mBrigthnessProgress+"%");
                int brigthnessVolume = (int)((mMaxBrigthness/100f)*mBrigthnessProgress);

                map.clear();
                map.put(EventBusEvent.BRIGHTNES_CHANGE, brigthnessVolume);
                EventBus.getDefault().post(map);
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });
    }

    public void initSound(){
       if(inflate == null){
           return;
       }

        int currentVolume = getAudioManager().getStreamVolume(AudioManager.STREAM_MUSIC);
        //媒体音量 STREAM_MUSIC    STREAM_RING 铃声音量
        int mMaxVolume = getAudioManager().getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volumeProgress = (int)((currentVolume/(mMaxVolume*1f))*100f);
        HashMap<Object, Object> map = new HashMap<>();
        rsbSound.setRange(0,100);
        rsbSound.setProgress(volumeProgress);
//        tvSoundNum.setText(volumeProgress +"%");
        rsbSound.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                if(isFirstSound){
                    isFirstSound = false;
                    return;
                }
                mSoundProgress = (int) (leftValue + 0.0001);
//                tvSoundNum.setText(mSoundProgress+"%");

                int volume = (int) ((mMaxVolume/100f)*mSoundProgress);

                map.clear();
                map.put(EventBusEvent.VOICE_CHANGE, volume);
                EventBus.getDefault().post(map);
                if(volume <= 0){
                    getAudioManager().setRingerMode(AudioManager.RINGER_MODE_SILENT);
                }else {
                    getAudioManager().setRingerMode(AudioManager.RINGER_MODE_NORMAL);

                }
                //设置铃声音量
                getAudioManager().setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);

            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });

    }
    private AudioManager getAudioManager() {
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        }
        return mAudioManager;
    }
    public void showAnimation(Context context,int type){
        if(inflate == null){
            initView(context,mActivity);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }

        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
        alphaAnimation.setDuration(500);
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                goneLayout();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    public void goneLayout(){
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.GONE);
            }
        }

    }


    /**
     * dp2px
     */
    protected int dp2px(float dpValue) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cl_setting:
                Intent intent = new Intent(mContext, SettingNewActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                break;
            case R.id.cl_wifi:
                intent = new Intent(mContext, SimpleWifiActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                break;
            case R.id.cl_bluetooth:
                if(Bluetooth.getInstance().isBluetoothOpened()){
                    intent = new Intent(mContext, SimpleBluetoothActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                }else {
                    ToastUtils.getInstance().show(mContext,mContext.getString(R.string.app_bluetooth_no_open));
                    return;
                }
                break;
        }
        goneLayout();
    }
}
